<template>
  <div class="center_management_wrapper">
    <!-- 主要页面 -->
    <div class="main_page">
      <!-- 筛选框部分 -->
      <div class="search_part">
        <span style="margin-right: 12px">中心编号：</span>
        <el-input style="margin-right: 12px; width: 10%" v-model="searchInputValue" size="mini"></el-input>
        <el-button style="margin-right: 12px" type="primary" size="mini" icon="el-icon-search" @click="handleSearch()"
        >查询</el-button
        >
        <el-button style="margin-right: 12px" size="mini" icon="el-icon-refresh" @click="handleReset()">重置</el-button>
        <el-button style="margin-right: 12px" type="primary" size="mini" icon="el-icon-plus" @click="handleAdd()"
        >新增</el-button
        >
      </div>
      <!-- 表格部分 -->
      <div class="table_part">
        <el-table :data="tableData" :header-cell-style="{ background: 'rgba(117, 60, 202, 0.04)' }" :stripe="true">
          <el-table-column prop="coreCode" align="center" label="中心编号"></el-table-column>
          <el-table-column prop="coreName" align="center" label="中心名称"></el-table-column>
          <el-table-column prop="isMain" align="center" label="主中心">
            <template v-slot="{ row }">
              <el-tag v-if="row.isMain === 1">是</el-tag>
              <el-tag v-if="row.isMain === 0" type="info">否</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="takeStatus" align="center" label="参与状态">
            <template v-slot="{ row }">
              <el-tag v-if="row.takeStatus === 1">是</el-tag>
              <el-tag v-if="row.takeStatus === 0" type="info">否</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="beginDate" align="center" label="参与日期"></el-table-column>
          <el-table-column prop="stopDate" align="center" label="结束日期"></el-table-column>
          <el-table-column align="center" label="操作" min-width="120">
            <template v-slot="{ row }">
              <el-button size="mini" icon="el-icon-edit" @click="handleEdit(row)">编辑</el-button>
              <el-button
                size="mini"
                icon="el-icon-delete"
                type="danger"
                @click="handleDelete(row)"
              >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
        <el-row type="flex" justify="end" style="margin-top: 24px">
          <el-pagination
            @size-change="handleSizeChange($event)"
            @current-change="handleCurrentChange($event)"
            :current-page="pageParams.pageNo"
            :page-size="pageParams.pageSize"
            :page-sizes="[10, 20, 50]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="pageParams.total"
          >
          </el-pagination>
        </el-row>
      </div>
    </div>
    <!-- 弹窗部分 -->
    <el-dialog :visible="addDiaVis" width="600px" :title="diaTitle" @close="handleAddDiaCancel()">
      <el-form ref="formRef" :model="formData" :rules="formRules" label-width="120px">
        <div v-for="item in formColumns" :key="item.prop">
          <el-form-item v-if="item.isShow" :label="item.label" :prop="item.prop">
            <!-- 输入下拉框 -->
            <CentralRollingSelect
              v-if="item.ele === 'inputSelect'"
              :value="formData[item.prop]"
              @change="onRollingSelectChange($event)"
              :width="80"
            ></CentralRollingSelect>
            <!-- 下拉框 -->
            <el-select size="mini" v-if="item.ele === 'select'" v-model="formData[item.prop]" style="width: 80%">
              <el-option v-for="it in item.options" :key="it.value" :value="it.value" :label="it.label"></el-option>
            </el-select>
            <!-- 输入框 -->
            <el-input
              :disabled="item.disabled"
              size="mini"
              v-if="item.ele === 'input'"
              v-model="formData[item.prop]"
              style="width: 80%"
            ></el-input>
            <!-- 单选按钮 -->
            <el-radio-group v-if="item.ele === 'radio'" v-model="formData[item.prop]">
              <el-radio v-for="item in item.radioOptions" :key="item.value" :label="item.value">{{
                item.label
              }}</el-radio>
            </el-radio-group>
            <!-- 时间选择 -->
            <el-date-picker
              size="mini"
              v-if="item.ele === 'datePicker'"
              v-model="formData[item.prop]"
              type="date"
              placeholder="选择日期"
              style="width: 80%"
              value-format="yyyy-MM-dd"
            >
            </el-date-picker>
          </el-form-item>
        </div>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleAddDiaCancel()" size="mini">取 消</el-button>
        <el-button type="primary" @click="handleAddDiaConfirm()" size="mini">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { mapActions } from 'vuex'
import CentralRollingSelect from './components/central-rolling-select.vue'

export default {
  components: {
    CentralRollingSelect,
  },
  data() {
    return {
      // 搜索框值
      searchInputValue: '',
      // 页码参数
      pageParams: {
        pageNo: 1,
        pageSize: 10,
        total: null,
      },
      // 弹窗显示
      addDiaVis: false,
      // 弹窗表单渲染
      formColumns: [
        { label: '选择医院：', prop: 'hospitalId', ele: 'inputSelect', disabled: false, isShow: true },
        { label: '中心名称：', prop: 'coreName', ele: 'input', disabled: true, isShow: true },
        { label: '中心编号：', prop: 'coreCode', ele: 'input', disabled: false, isShow: true },
        {
          label: '主中心：',
          prop: 'isMain',
          ele: 'radio',
          radioOptions: [
            { label: '是', value: 1 },
            { label: '否', value: 0 },
          ],
          disabled: false,
          isShow: true,
        },
        { label: '目标版本：', prop: 'versionId', ele: 'select', disabled: false, isShow: true, options: [] },
        {
          label: '参与状态：',
          prop: 'takeStatus',
          ele: 'radio',
          radioOptions: [
            { label: '是', value: 1 },
            { label: '否', value: 0 },
          ],
          disabled: false,
          isShow: true,
        },
        { label: '参与日期：', prop: 'beginDate', ele: 'datePicker', disabled: false, isShow: true },
        { label: '结束日期：', prop: 'stopDate', ele: 'datePicker', disabled: false, isShow: true },
      ],
      // 弹窗表单数据
      formData: {
        hospitalId: '',
        coreName: '',
        coreCode: '',
        isMain: 0,
        versionId: '',
        takeStatus: 1,
        beginDate: '',
        stopDate: '',
        province: '',
        city: '',
        area: '',
      },
      defaultFormData: {
        hospitalId: '',
        coreName: '',
        coreCode: '',
        isMain: 0,
        versionId: '',
        takeStatus: 1,
        beginDate: '',
        stopDate: '',
        province: '',
        city: '',
        area: '',
      },
      // 弹窗表单校验
      formRules: {
        hospitalId: [{ required: true, message: '请填写', trigger: 'blur' }],
        coreCode: [{ required: true, message: '请填写', trigger: 'blur' }],
        versionId: [{ required: true, message: '请填写', trigger: 'blur' }],
      },
      // 表格数据
      tableData: [],
      diaIsAdd: true,
      projectId: '',
      projectDatabaseId: '',
      diaTitle: '新增',
      localCoreIds: [],
    }
  },

  created() {
    this.projectId = localStorage.getItem('sys-project-id') || ''
    this.projectDatabaseId = localStorage.getItem('project-database-Id') || ''
    this.getTargetVersionOptions()
    this.getCentralManagement()
  },
  methods: {
    ...mapActions('centralManagement', [
      'getCentralManagementAPI',
      'deleteCentralManagementAPI',
      'addCentralManagementAPI',
      'updateCentralManagementAPI',
      'getDatabaseVersionListAPI',
    ]),

    // 获取目标版本下拉项
    async getTargetVersionOptions() {
      const params = {
        projectId: this.projectId,
        projectDatabaseId: this.projectDatabaseId,
      }
      const res = await this.getDatabaseVersionListAPI({ params })
      this.formColumns[4].options = res.data.map(item => ({
        label: item.useVersion + '(' + item.databaseNum + ')',
        value: item.id,
      }))
    },

    // 获取表格数据
    async getCentralManagement() {
      const params = {
        ...this.pageParams,
        projectId: this.projectId,
        projectDatabaseId: this.projectDatabaseId,
        coreCode: this.searchInputValue,
      }
      const res = await this.getCentralManagementAPI({ params })
      if (res.code === 200) {
        res.data.records.sort((a, b) => a.coreCode - b.coreCode)
        this.tableData = res.data.records
        this.pageParams.pageNo = res.data.current
        this.pageParams.total = res.data.total
      }
      const coreIdsArr = []
      res.data.records.forEach(item => {
        coreIdsArr.push(item.coreId)
      })
      this.localCoreIds = JSON.parse(localStorage.getItem('coreIds'))
      const mergedArray = this.localCoreIds.concat(coreIdsArr.filter(item => !this.localCoreIds.includes(item)))
      localStorage.setItem('coreIds', JSON.stringify(mergedArray))
    },
    // 输入下拉框选择
    onRollingSelectChange(obj) {
      if (!obj.label) {
        this.formData.coreName = ''
        return false
      }
      const index = obj.label.indexOf('/')
      let string = ''
      if (index !== -1) {
        string = obj.label.substring(0, index)
        this.formData.coreName = string
      } else {
        this.formData.coreName = obj.label
      }
      this.formData.hospitalId = obj.value
      this.formData.province = obj.provinceVO.id + ''
      this.formData.city = obj.cityVO.id + ''
      this.formData.area = obj.areaVO.id + ''
    },

    // 点击新增
    handleAdd() {
      this.diaTitle = '新增'
      this.addDiaVis = true
      this.diaIsAdd = true
      this.formColumns.forEach(item => {
        item.isShow = true
      })
    },
    // 点击搜索
    handleSearch() {
      this.pageParams.pageNo = 1
      this.pageParams.pageSize = 10
      this.getCentralManagement()
    },
    // 点击重置
    handleReset() {
      this.searchInputValue = ''
      this.pageParams.pageNo = 1
      this.pageParams.pageSize = 10
      this.pageParams.total = null
      this.getCentralManagement()
    },
    // 点击编辑
    handleEdit(row) {
      this.diaTitle = '编辑'
      this.diaIsAdd = false
      this.formData = {
        ...row,
      }
      this.addDiaVis = true
      this.formColumns[0].isShow = false
      this.formColumns[4].isShow = false
    },
    // 点击删除
    async handleDelete(row) {
      const params = {
        id: row.id,
      }
      const res = await this.deleteCentralManagementAPI({
        params,
      })
      if (res.code === 200) {
        this.$message.success('删除成功')
        const pageLastOne =
          this.pageParams.total % this.pageParams.pageSize === 1 &&
          Math.floor(this.pageParams.total / this.pageParams.pageSize) === this.pageParams.pageNo - 1
        if (pageLastOne) {
          if (this.pageParams.pageNo !== 1) {
            this.pageParams.pageNo = this.pageParams.pageNo - 1
          }
        }
        this.getCentralManagement()
      }
    },
    // 新增公共关闭
    publicCloseAdd() {
      this.$refs.formRef.resetFields()
      this.addDiaVis = false
      this.formData = {
        ...this.defaultFormData,
      }
    },

    // 新增取消
    handleAddDiaCancel() {
      this.publicCloseAdd()
    },

    // 新增确认
    async handleAddDiaConfirm() {
      await this.$refs.formRef.validate()
      this.formData.databaseVersionIds = [this.formData.versionId]
      this.formData.hospitalName = this.formData.coreName
      const data = {
        ...this.formData,
        projectId: this.projectId,
        projectDatabaseId: this.projectDatabaseId,
      }
      if (this.diaIsAdd) {
        const res = await this.addCentralManagementAPI({ data })
        if (res.code === 200) {
          this.publicCloseAdd()
          this.$message.success('新增成功')
          this.getCentralManagement()
        }
      } else if (!this.diaIsAdd) {
        const res = await this.updateCentralManagementAPI({ data })
        if (res.code === 200) {
          this.publicCloseAdd()
          this.$message.success('修改成功')
          this.getCentralManagement()
        }
      }
    },
    // 页码变化
    handleCurrentChange(currentPage) {
      this.pageParams.pageNo = currentPage
      this.getCentralManagement()
    },
    handleSizeChange(currentSize) {
      this.pageParams.pageSize = currentSize
      this.getCentralManagement()
    },
  },
}
</script>

<style lang="scss" scoped>
.center_management_wrapper {
  background-color: $white;
  height: 100%;
  .main_page {
    background-color: $white;
    padding: 12px;
    .table_part {
      margin-top: 24px;
    }
  }
}
</style>
